package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

// 获取普通用户
func admingetHandler(w http.ResponseWriter, r *http.Request) {

	method := r.Method
	if method == "POST" {

		var commonuser []User
		rows, err := db.Query(context.Background(), "SELECT * FROM shopping.p_user WHERE role = 'comuser'")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var user User
			err := rows.Scan(&user.UserType, &user.Username, &user.Phonenumber, &user.Idnumber, &user.Email, &user.Password)
			if err != nil {
				fmt.Println(err)
			}
			// fmt.Println(user.UserType, user.Username, user.Phonenumber, user.Email, user.Idnumber, user.Password)
			commonuser = append(commonuser, user)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(commonuser) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(commonuser))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(commonuser)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

}

// 获取商户
func admingettHandler(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	if method == "POST" {

		var businessuser []User
		rows, err := db.Query(context.Background(), "SELECT * FROM shopping.p_business WHERE role = 'business'")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var user User
			err := rows.Scan(&user.UserType, &user.Username, &user.Phonenumber, &user.Idnumber, &user.Email, &user.Password)
			if err != nil {
				fmt.Println(err)
			}
			businessuser = append(businessuser, user)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(businessuser) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(businessuser))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(businessuser)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}

// 管理用户与商户
func adminmgrHandler(w http.ResponseWriter, r *http.Request) {

	switch r.Method {
	//增加用户
	case "POST":
		var user1 User
		err := json.NewDecoder(r.Body).Decode(&user1)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//fmt.Println(user1)
		if user1.UserType == "business" {
			_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_business (role, username, password, email, idnumber, phonenumber) VALUES ($1, $2, $3, $4, $5,$6)", user1.UserType, user1.Username, user1.Password, user1.Email, user1.Idnumber, user1.Phonenumber)
		} else {
			_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_user (role,username, password, email, idnumber, phonenumber) VALUES ($1, $2, $3, $4, $5,$6)", user1.UserType, user1.Username, user1.Password, user1.Email, user1.Idnumber, user1.Phonenumber)
		}

		if err != nil {
			fmt.Println("Insert error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "User added successfully")

	//修改用户
	case "PUT":
		var user2 User
		err := json.NewDecoder(r.Body).Decode(&user2)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}

		//更新数据库的用户
		if user2.UserType == "business" {
			_, err = db.Exec(context.Background(), "UPDATE shopping.p_business SET username=$1, phonenumber=$2, email=$3, idnumber=$4, password=$5 ,role=$6 WHERE username=$7", user2.Username, user2.Phonenumber, user2.Email, user2.Idnumber, user2.Password, user2.UserType, user2.Username)

		} else {
			_, err = db.Exec(context.Background(), "UPDATE shopping.p_user SET username=$1, phonenumber=$2, email=$3, idnumber=$4, password=$5 ,role=$6 WHERE username=$7", user2.Username, user2.Phonenumber, user2.Email, user2.Idnumber, user2.Password, user2.UserType, user2.Username)

		}

		if err != nil {
			fmt.Println("Update error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "User updated successfully")

	//删除用户
	case "DELETE":
		var user3 User
		err := json.NewDecoder(r.Body).Decode(&user3)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//删除数据库的用户
		if user3.UserType == "business" {
			_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_business WHERE username=$1", user3.Username)
		} else {
			_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_user WHERE username=$1", user3.Username)
		}

		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "User deleted successfully")

	}
}

// 审批商店
func shopauditHandler(w http.ResponseWriter, r *http.Request) {

	switch r.Method {
	// 将所有商店信息传给前端
	case "POST":
		var shops []Returnshopinfo
		rows, err := db.Query(context.Background(), "SELECT shopname,category,idnumber,introduce,address,money,createtime,state,owner,imagename FROM shopping.p_shopinfo WHERE  state= 'audit'")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var tempdate time.Time
			var shop Returnshopinfo
			err := rows.Scan(&shop.ShopName, &shop.Category, &shop.Idnumber, &shop.Introduce, &shop.Address, &shop.Money, &tempdate, &shop.State, &shop.Owner, &shop.Imagename)
			if err != nil {
				fmt.Println(err)
			}
			shop.Createtime = tempdate.Format("2006-01-02 15:04:05")

			//fmt.Println(shop)
			shops = append(shops, shop)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(shops) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(shops))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(shops)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	//同意审批
	case "PUT":
		var shopstate struct {
			Shopname string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shopstate)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//更新数据库
		_, err = db.Exec(context.Background(), "UPDATE shopping.p_shopinfo SET state='pass' WHERE shopname=$1", shopstate.Shopname)
		if err != nil {
			fmt.Println("Update error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Shop updated successfully")
	//拒绝审批
	case "DELETE":
		var shopstate struct {
			Shopname string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shopstate)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//将审批结果删除
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_shopinfo WHERE shopname=$1", shopstate.Shopname)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Shop deleted successfully")
	}

}

// 管理商店
func shopmgrHandler(w http.ResponseWriter, r *http.Request) {

	switch r.Method {

	case "POST":
		var shops []Returnshopinfo
		rows, err := db.Query(context.Background(), "SELECT shopname,category,idnumber,introduce,address,money,createtime,state,owner,imagename FROM shopping.p_shopinfo WHERE  state= 'pass'")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {
			var tempdate time.Time
			var shop Returnshopinfo
			err := rows.Scan(&shop.ShopName, &shop.Category, &shop.Idnumber, &shop.Introduce, &shop.Address, &shop.Money, &tempdate, &shop.State, &shop.Owner, &shop.Imagename)
			if err != nil {
				fmt.Println(err)
			}
			shop.Createtime = tempdate.Format("2006-01-02")
			//fmt.Println("-------------------------------")
			//fmt.Println(shop)
			shops = append(shops, shop)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(shops) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(shops))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(shops)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//下架商店
	case "DELETE":
		var shopstate struct {
			Shopname string `json:"shopname"`
		}
		err := json.NewDecoder(r.Body).Decode(&shopstate)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		//fmt.Println(shopstate.Shopname)
		//将审批结果删除
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_shopinfo WHERE shopname=$1", shopstate.Shopname)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Shop deleted successfully")

	}

}

// 管理商品
func usrgoodmgrHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		var goods []Good
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_goods ")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var good Good
			err := rows.Scan(&good.Shopname, &good.Goodname, &good.Goodprice, &good.Goodcount)
			if err != nil {
				fmt.Println(err)
			}
			//fmt.Println("99999999999999999999999999")
			//fmt.Println(good)
			goods = append(goods, good)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(goods) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d goods\n", len(goods))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(goods)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	case "DELETE":
		var good Good
		err := json.NewDecoder(r.Body).Decode(&good)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//fmt.Println(good)
		//删除数据库的商品
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_goods WHERE shopname=$1 and goodname=$2", good.Shopname, good.Goodname)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}

// 流水记录获取
func purchaseinfomgrHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		var purchaseinfos []Purchaseinfo
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_purchase ")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var purchaseinfo Purchaseinfo
			err := rows.Scan(&purchaseinfo.Username, &purchaseinfo.Shopname, &purchaseinfo.Goodname, &purchaseinfo.Goodcount, &purchaseinfo.Goodprice, &purchaseinfo.Cost)
			if err != nil {
				fmt.Println(err)
			}
			//fmt.Println("99999999999999999999999999")
			//fmt.Println(purchaseinfo)
			purchaseinfos = append(purchaseinfos, purchaseinfo)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(purchaseinfos) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d purchases\n", len(purchaseinfos))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(purchaseinfos)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	case "DELETE":
		var purchaseinfo Purchaseinfo
		err := json.NewDecoder(r.Body).Decode(&purchaseinfo)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//fmt.Println(purchaseinfo)
		//删除数据库的商品
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_purchase WHERE username =$1 and shopname=$2 and goodname=$3 and goodcount=$4 and goodprice=$5 and cost=$6", purchaseinfo.Username, purchaseinfo.Shopname, purchaseinfo.Goodname, purchaseinfo.Goodcount, purchaseinfo.Goodprice, purchaseinfo.Cost)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}

// 管理员管理评论
func admincommentmgrHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		var comments []Comment
		// 查询数据库
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_comment")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {
			var tempdate time.Time
			var comment Comment
			err := rows.Scan(&comment.Username, &comment.Shopname, &comment.Goodname, &comment.Text, &tempdate)
			if err != nil {
				fmt.Println(err)
			}
			comment.Time = tempdate.Format("2006-01-02 15:04:05")
			// fmt.Println(comment.Time)
			// fmt.Println(tempdate)
			comments = append(comments, comment)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(comments) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d comments\n", len(comments))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(comments)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else if r.Method == "DELETE" {
		var comment Comment
		err := json.NewDecoder(r.Body).Decode(&comment)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//fmt.Println(comment)
		var tempdate time.Time
		tempdate, err = time.Parse("2006-01-02 15:04:05", comment.Time)
		if err != nil {
			fmt.Println(err)
		}
		//删除数据库评论
		_, err = db.Exec(context.Background(), "DELETE FROM shopping.p_comment WHERE time=$1", tempdate)
		if err != nil {
			fmt.Println("Delete error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
